package com.xcity.game.activity.gift;

import java.util.Map;
import java.util.TreeMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xcity.Server;
import com.xcity.db.entity.Player;
import com.xcity.game.activity.ActivityService;
import com.xcity.game.common.Cause;
import com.xcity.game.common.MessageConst;
import com.xcity.game.mail.MailAttach;
import com.xcity.pomelo.PomeloRoute;
import com.xcity.pomelo.request.GiftExchangeRequest;
import com.xcity.pomelo.response.HintResponse;
import com.xcity.pomelo.response.Response;
import com.xcity.util.HttpUtils;
import com.xcity.util.IdUtils;
import com.xcity.util.PlatformApi;

import naga.x.net.Session;
import naga.x.net.annotation.OPHandler;
import naga.x.net.impl.pomelo.annotation.PomeloOP;
import naga.x.service.ServiceException;
import naga.x.util.CommonUtils;
import naga.x.util.IOUtils;
import naga.x.util.StringUtils;

/**
 * 礼包兑换
 * @author yang.li
 *
 */
@OPHandler
public class GiftExchangeActivityService extends ActivityService {

//	protected TIntObjectMap<GiftExchangeTemplate> templates;
//	protected Map<String, ExchangeCode> codes = new ConcurrentHashMap<String, ExchangeCode>();
	
	public static final int CODE_BAD_REQUEST = -1; // 非法请求
	public static final int CODE_NOT_FOUND = -2; // 礼包码错误
	public static final int CODE_RECEIVED = -3; // 礼包已被领取
	public static final int CODE_NO_PERMISSION = -4; // 没有权限领取（eg.渠道限制）
	
	@Override
	public void startup() throws ServiceException {
//		templates = App.getApp().getServiceManager().get(TemplateService.class).getTemplates(GiftExchangeTemplate.class);
//		loadCodes();
	}
	
//	private void loadCodes() {
//		File file = new File(App.getApp().getConfig().getString(Config.DATA_DIR), "code.txt");
//		if (file.exists()) {
//			IOUtils.read(file, IOUtils.UTF8, new LineReaderListener() {
//				@Override
//				public boolean readLine(String line) {
//					if ((line = line.trim()).length() > 0) {
//						ExchangeCode ec = ExchangeCode.parse(line);
//						codes.put(ec.getCode(), ec);
//					}
//					return true;
//				}
//			});
//		}
//	}

	@Override
	public void shutdown() throws ServiceException {
//		StringBuilder buf = new StringBuilder(1024);
//		Collection<ExchangeCode> vals = codes.values();
//		for (ExchangeCode ec : vals) {
//			buf.append(ec.toString()).append(System.lineSeparator());
//		}
//		IOUtils.write(new File(App.getApp().getConfig().getString(Config.DATA_DIR), "code.txt"), buf.toString(), IOUtils.UTF8);
	}
	
	@PomeloOP(PomeloRoute.GIFT_EXCHANGE_REQUEST)
	protected void requestExchange(Session session, final GiftExchangeRequest req) {
		String code = req.getCode();
		if (StringUtils.isEmpty(code)) {
			session.send(new HintResponse(req.getSerial(), MessageConst.EXCHANGE_CODE_EMPTY));
			return;
		}
		Player player = session.getClient();
		Map<String, String> params = new TreeMap<>();
		params.put("channel", String.valueOf(player.getAccount().getChannel().ordinal()));
		params.put("sid", String.valueOf(IdUtils.serverId));
		params.put("pid", String.valueOf(player.getId()));
		params.put("code", code);
		params.put("sign", Server.makeSign(params));
		String s = HttpUtils.post(PlatformApi.codeUrl, params);
		JSONObject res = JSON.parseObject(CommonUtils.decodeURL(s, IOUtils.UTF8));
		if (res == null) {
			session.send(new HintResponse(req.getSerial(), MessageConst.OP_TIME_OUT));
			return;
		}
		int resCode = res.getIntValue("code");
		if (resCode == CODE_RECEIVED) {
			session.send(new HintResponse(req.getSerial(), MessageConst.EXCHANGE_RECEIVED));
			return;
		}
		if (resCode == CODE_NO_PERMISSION) {
			session.send(new HintResponse(req.getSerial(), MessageConst.EXCHANGE_CAN_NOT_RECEIVE));
			return;
		}
		if (resCode != 0) {
			session.send(new HintResponse(req.getSerial(), MessageConst.EXCHANGE_CODE_INVALID));
			return;
		}
		MailAttach content = res.getObject("content", MailAttach.class);
		if (content == null) {
			session.send(new HintResponse(req.getSerial(), MessageConst.SYSTEM_ERROR));
			return;
		}
		content.receive(player, Cause.EXCHANGE, true);
		session.send(new Response(req.getSerial()));
		LOG.info("[GIFTEXCHANGE]ID[{}]CODE[{}]", player.getId(), code);
	}
	
	
}
